import { BadRequestException, ValidationError } from '@nestjs/common'
import { ErrorDto } from '@boticord/response-serializer'

export const exceptionFactory = (errors: ValidationError[]) => {
  const processError = (err: ValidationError) => {
    if (err.contexts) {
      for (const key of Object.keys(err.contexts)) {
        const context = err.contexts[key]
        const code = +(context?.code ?? context)
        const message = context?.message ?? err.constraints?.[key] ?? 'google en passant holy hell'

        errs.push({
          code, message,
        })
      }
    } else {
      for (const constraint of Object.values(err.constraints ?? {})) {
        errs.push({ code: 0, message: constraint })
      }
    }

    for (const child of err.children ?? []) {
      processError(child)
    }
  }
  const errs: ErrorDto[] = []
  errors.forEach(processError)

  return new BadRequestException({ errors: errs })
}